import currencyRoutes from "../../router/modules/currencyRoutes";

const Layout = {
  namespaced: true,
  state: {
    /**
     * layoutAside
     */
    isCollapse: false,
    CurrentPage: {
      path: "",
      breadcrumbs: []
    },
    // page bar
    pageBarShow: true,
    pageTags: [],
    // keepLive缓存
    cachePages: []
  },
  mutations: {
    // 侧边栏展开关闭控制
    toggleCollapse (state) {
      state.isCollapse = !state.isCollapse;
    },
    // 加入缓存
    addCachePage (state, pageName) {
      state.cachePages.push(pageName);
    },
    // 删除缓存
    delCachePage (state, pageName) {
      state.cachePages = state.cachePages.filter(item => {
        return item != pageName;
      });
    },
    // 当前页面路由信息
    setActivePath (state, routerInfo) {
      state.CurrentPage.path = routerInfo.path;
      state.CurrentPage.breadcrumbs = routerInfo.breadcrumbs;
    },
    // PageBar关闭控制
    PageBarCollapse (state) {
      state.pageBarShow = !state.pageBarShow;
    },
    addPageTag (state, tag) {
      state.pageTags.push(tag);
    },
    closePageTag (state, index) {
      state.pageTags.splice(index, 1);
    },
    closeOtherTag (state, path) {
      let cuted = state.pageTags.filter(item => {
        return path === item.path;
      });
      let _cachePages = [];
      cuted.forEach(item => {
        _cachePages.push(item.name);
      });
      state.pageTags = cuted;
      state.cachePages = _cachePages;
    },
    closeLeftTag (state, index) {
      let deletedList = state.pageTags.splice(0, index);
      deletedList.forEach(item => {
        this.commit("Layout/delCachePage", item.name);
      });
    },
    closeRightTag (state, index) {
      let deletedList = state.pageTags.splice(index + 1);
      deletedList.forEach(item => {
        this.commit("Layout/delCachePage", item.name);
      });
    },
    closeAllTag (state) {
      state.pageTags = [];
      state.cachePages = [];
    }
  },
  actions: {
    saveActivePage ({ state, commit }, matched) {
      // 提取CurrentPage
      let breadcrumbs = [];
      matched.forEach(item => {
        // 只提取有用数据
        let { meta, path } = item;
        if (meta.title) {
          breadcrumbs.push({ meta, path });
        }
      });
      let CurrentRoute = matched[matched.length - 1];
      commit("setActivePath", { path: CurrentRoute.path, breadcrumbs });

      // 提取pageTags
      let pageTags = state.pageTags;
      if (CurrentRoute.meta && !CurrentRoute.meta.notKeep) {
        // 将页面加入缓存
        commit("addCachePage", CurrentRoute.name);
      }

      let { name, meta, path } = CurrentRoute;
      if (path === "/dashbord") return;
      let findIndex = false;
      pageTags.forEach(item => {
        if (item.path == path) {
          findIndex = true;
          return;
        }
      });
      findIndex ? "" : commit("addPageTag", { name, meta, path });
    }
  }
};
export default Layout;
